import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
var tableArray = [{id:100,rightKey:'1',text:'⬉'},
{id:101,rightKey:'一',text:'✚'},
{id:102,rightKey:'4',text:'⬊'},
{id:103,rightKey:'一',text:'✚'},
{id:104,rightKey:'2',text:'⬈'},
{id:105,rightKey:'二',text:'✚'},
{id:106,rightKey:'二',text:'✚'},
{id:107,rightKey:'1',text:'⬉'},
{id:108,rightKey:'3',text:'⬋'},
{id:109,rightKey:'2',text:'⬈'},
{id:110,rightKey:'三',text:'✚'},
{id:111,rightKey:'4',text:'⬊'},
{id:112,rightKey:'三',text:'✚'},
{id:113,rightKey:'3',text:'⬋'},
{id:114,rightKey:'3',text:'⬋'},
{id:115,rightKey:'2',text:'⬈'},
{id:116,rightKey:'四',text:'✚'},
{id:117,rightKey:'4',text:'⬊'},
{id:118,rightKey:'四',text:'✚'},
{id:119,rightKey:'1',text:'⬉'},
{id:120,rightKey:'3',text:'⬋'},
]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    itemArray: ['一', '二', '三', '四'],
    numberArray: ['1', '2', '3', '4'],
    tableArray,
    countdownTime: 60,//页面倒计时
    activeIndex: -1, // 用于记录随机选中项的索引
    practiceCorrectIndex: -1, // 记录练习题答对的索引
    totalCount: 0, //题目总数
    count: 0, //记录做题次数
    isExercise: true, //是否是练习题
    questionIndex:0,//当前题型索引
    countdownInterval: null, // 存储 interval ID
    isShowTip: false, //练习结束提示
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },
  onLoad() {
    this.getTopicData();
    this.setRandomActive(); // 页面加载时设置随机激活项

    // 初始化时加载已有的答题记录
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    this.setData({
      answerRecords: savedAnswerRecords
    });
  },
  getTopicData(){
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count} = util.getData(questionIndex);
    this.setData({
      totalCount:count,
      questionIndex
    })
  },
  // 添加设置随机激活项的方法
  setRandomActive() {
    const { tableArray, practiceCorrectIndex, isExercise } = this.data;
    let randomIndex;
    
    if (!isExercise && practiceCorrectIndex !== -1) {
      // 正式题阶段，确保不选择练习题答对的那个索引
      do {
        randomIndex = Math.floor(Math.random() * tableArray.length);
      } while (randomIndex === practiceCorrectIndex);
    } else {
      // 练习题阶段或还未答对练习题时，可以随机选择任何索引
      randomIndex = Math.floor(Math.random() * tableArray.length);
    }
    
    this.setData({
      activeIndex: randomIndex,
      // 记录题目开始时间
      questionStartTime: new Date().getTime()
    });
    // 每道题目开始倒计时
    this.startCountdown();
  },
   
  // 倒计时
  startCountdown() {
    const that = this;
    let {count,totalCount,isExercise} = that.data;
    // 清除已有倒计时
    if (that.data.countdownInterval) {
      clearInterval(that.data.countdownInterval);
    }
    that.setData({
      countdownTime: 60
    });
    const interval = setInterval(() => {
      const newTime = that.data.countdownTime - 1;
      if (newTime > 0) {
        that.setData({
          countdownTime: newTime
        });
      } else {
        clearInterval(interval);
        // 倒计时结束，视为错误
        wx.showToast({
          title: '已超时',
          icon: 'none',
          duration: 1000
        });
        setTimeout(() => {
          if (isExercise) {
            that.setRandomActive();
          } else {
            // 使用共用方法创建并保存答题记录
            const newAnswerRecords = this.createAndSaveAnswerRecord(true);

            // 无论对错都增加总次数
            let countNum = count + 1;
            that.setData({
              count:countNum,
              answerRecords: newAnswerRecords
            })
            // 判断题目次数，跳转并打印结果
            if (countNum >= totalCount) {
              //跳转下一题
              let questionNumber = that.data.questionIndex + 1;
              const prevInfo = wx.getStorageSync('questionInfo') || {};
              wx.setStorageSync('questionInfo', {
                ...prevInfo,
                questionNumber
              });
              util.navigateByDesc(questionNumber);
            } else {
              // 继续下一题
              that.setRandomActive();
            }
          }
        }, 1000);
      }
    }, 1000);
    that.setData({
      countdownInterval: interval
    });
  },
  // 提交
  onSubmit(e) {
    let value = e.currentTarget.dataset.value;
    let {count,activeIndex,tableArray,isExercise,totalCount} = this.data;
    const answer = tableArray[activeIndex].rightKey;
    let isCorrect;
    if (value === answer) {
      isCorrect = true
    } else {
      isCorrect = false
    }
    if (isExercise) {
      if (value === answer) {
        this.setData({
          isExercise: false,
          isShowTip: true,
          practiceCorrectIndex: activeIndex // 保存答对题目的索引
        })
      } else {
        this.setRandomActive();
      }
    } else {
       // 使用共用方法创建并保存答题记录
      const newAnswerRecords = this.createAndSaveAnswerRecord(false, value,isCorrect,answer);

      // 无论对错都增加总次数
      let countNum = count + 1;
      this.setData({
        count:countNum,
        answerRecords: newAnswerRecords
      })
      // 判断题目次数，跳转并打印结果
      if (countNum >= totalCount) {
        //跳转下一题
        let questionNumber = this.data.questionIndex + 1;
        const prevInfo = wx.getStorageSync('questionInfo') || {};
        wx.setStorageSync('questionInfo', {
          ...prevInfo,
          questionNumber
        });
        util.navigateByDesc(questionNumber);
      } else {
        // 继续下一题
        this.setRandomActive();
      }
    }
  },
   // 开始测试
   onStar() {
    this.setData({
      isShowTip: false,
    })
    this.setRandomActive();
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '',isRight = false,answer) {
    const {questionStartTime,questionIndex} = this.data;
    const questionList = wx.getStorageSync('questionInfo').questionList;
    const currentTopic = questionList[questionIndex]

    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);
    
    // 判断是否正确（超时视为错误）
    let option = '';
    
    if (!isTimeout) {
      option = userOption;
      isRight =  isRight? 1 : 0;
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: 0,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.typeCode,
      stem: '',
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: answer,
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },

  onUnload() {
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
     // 页面卸载时确保答题记录已保存
     answerUtil.saveAnswerRecords(this.data.answerRecords);
  },
});